package com.yaoxun.console.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.yaoxun.console.constant.CacheConstant;
import com.yaoxun.console.exception.ValidatorException;
import com.yaoxun.console.xo.req.NamespaceEditReq;
import com.yaoxun.console.xo.req.NamespaceListReq;
import com.yaoxun.console.xo.resp.NamespaceResp;
import com.yaoxun.console.xo.resp.PageInfo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class NamespaceService {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private RouterService routerService;
	
	public void checkExist(String namespace) {		
		Long rank = stringRedisTemplate.opsForZSet().rank(CacheConstant.NAMESPACE, namespace);
		if(rank == null) {			
			throw new ValidatorException("命名空间【"+namespace+"】不存在");
		}
	}
	
	public void add(NamespaceEditReq req) {
		
		Long rank = stringRedisTemplate.opsForZSet().rank(CacheConstant.NAMESPACE, req.getNamespace());
		
		if(rank != null) {
			throw new ValidatorException("命名空间【"+req.getNamespace()+"】已经存在");
		}
		
		stringRedisTemplate.opsForZSet().add(CacheConstant.NAMESPACE, req.getNamespace(), System.currentTimeMillis());
	}

	public PageInfo<NamespaceResp> list(NamespaceListReq req) {
		
		if(StringUtils.isBlank(req.getOrder())) {
			req.setOrder("desc");
		}
		
		PageInfo<NamespaceResp> pageInfo = new PageInfo<>();
		
		Set<String> set = null;
		
		if(StringUtils.isBlank(req.getOrder()) || "desc".equals(req.getOrder())) {
			set = stringRedisTemplate.opsForZSet().reverseRange(CacheConstant.NAMESPACE, 0, -1);
		} else {
			set = stringRedisTemplate.opsForZSet().range(CacheConstant.NAMESPACE, 0, -1);
		}
		
		List<NamespaceResp> records = new ArrayList<>();
		
		for(String ns : set) {
			NamespaceResp record = new NamespaceResp();
			record.setNamespace(ns);
			records.add(record);
		}
		
		pageInfo.setRecords(records);
		
		return pageInfo;
	}

	
	public void delete(NamespaceEditReq req) {
		
		checkExist(req.getNamespace());

		boolean existRouters = routerService.getExistRouters(req.getNamespace());
		
		if(existRouters) {
			throw new ValidatorException("命名空间【"+req.getNamespace()+"】已经存在路由，无法直接删除");
		}
		
		Long count = stringRedisTemplate.opsForZSet().remove(CacheConstant.NAMESPACE, req.getNamespace());
		
		log.info("namespace remove count:{}", count);
		
	}
	
}
